package tt.dz.order.service.rpc.rpchander;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import org.apache.avro.generic.GenericRecord;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import tt.dz.order.exception.BusinessException;
import tt.dz.order.service.OrderService;
import tt.dz.order.vo.Order2WeiXinOrderRequestVo;
import tt.dz.order.vo.Order2WeiXinOrderResponseVo;
import tt.dz.order.vo.RetVO;

/**
 * 根据订单信息生成微信订单接口处理类 并返回对应的jsApj相关参数
 * 
 * @author NIBO
 *
 */
@Component("Order2WeiXinOrderHander")
public class Order2WeiXinOrderHander implements BaseHander {
	private static Logger log = LoggerFactory.getLogger(Order2WeiXinOrderHander.class);
	@Autowired
	OrderService orderService;

	@Override
	public RetVO dohander(GenericRecord req) {
		RetVO retVO = new RetVO(RetVO.SuccessCode, null, null);
		// 根据订单号查询订单项
		// try {
		String reqStr = req.get("request").toString();
		log.info("根据订单信息生成微信订单reqStr：" + reqStr);
		Order2WeiXinOrderRequestVo order2WeiXinOrderRequestVo = JSON.parseObject(reqStr,
				Order2WeiXinOrderRequestVo.class);
		Order2WeiXinOrderResponseVo orderInfoVo;
		try {
			orderInfoVo = orderService.order2WeiXinOrder(order2WeiXinOrderRequestVo);
			retVO.setBizData(orderInfoVo);
		} catch (UnsupportedEncodingException e) {
			// 验证返回签名失败
			log.error("验证返回签名失败", e);
			retVO.setErrorMsg("微信返回验证返回签名失败");
			retVO.setRetCode(RetVO.FailCode);
			retVO.setResultCode("1020300");
		} catch (BusinessException e) {
			log.error(e.getMessage());
			retVO.setErrorMsg(e.getMessage());
			retVO.setRetCode(RetVO.FailCode);
			retVO.setResultCode("1020300");
		} catch (DocumentException e) {
			// Xml2Map数据解析失败
			log.error("微信返回Xml2Map数据解析失败", e);
			retVO.setErrorMsg("微信返回Xml2Map数据解析失败");
			retVO.setRetCode(RetVO.FailCode);
			retVO.setResultCode("1020300");
		}
		return retVO;
	}

}
